<template>
  <contentModel v-if="editModelShow" title="按品类添加" @close="handleClose">
    <a-layout style="height: 100%" :class="screenClass">
      <a-layout>
        <a-layout-content>
          <query-form
            :render-config="formRenderConfig"
            :render-keys="cateRenderKeys"
            @search="searchHandle"
            @reset="resetHandle"
          />
          <table-container
            v-model:columns="cateColumns"
            v-model:is-fullscreen="isFullscreen"
            :loading="false"
            width="center"
          >
            <a-table
              v-model:selectedKeys="attrSelectedKeys"
              class="table"
              :columns="cateColumns"
              :data="cateDatalist"
              :row-selection="rowSelection"
              row-key="id"
              show-empty-tree
              style="height: 60vh; margin-top: 20px"
              :pagination="false"
              @select="selectItem"
              @selection-change="handleSelectionChange"
            >
              <template #secretLevel="{ record }">
                <secretLevelInfo
                  :record="{
                    secretLevel: record.secretLevel,
                    secretLevelName: record.secretLevelName,
                  }"
                />
              </template>
            </a-table>
          </table-container>
        </a-layout-content>
        <a-layout-sider width="20%" style="margin-left: 16px"
          ><a-list :size="size">
            <template #header> 已选品类 </template>
            <a-list-item v-for="(item, index) in selectAttrList" :key="index">
              <a-row>
                <a-col :span="4">
                  <secretLevelInfo
                    :record="{
                      secretLevel: item.secretLevel,
                      secretLevelName: item.secretLevelName,
                    }"
                  />
                </a-col>
                <a-col :span="19">
                  {{ item.categoryName }}
                </a-col>
                <a-col :span="1">
                  <div
                    style="float: right; cursor: pointer"
                    @click="deleteItem(item, index)"
                  >
                    x
                  </div>
                </a-col>
              </a-row>
            </a-list-item>
          </a-list></a-layout-sider
        >
      </a-layout>
    </a-layout>
    <template #footer>
      <a-button @click="handleClose">取消</a-button>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </template>
  </contentModel>
</template>

<script setup lang="ts">
  import {
    formRenderConfig,
    cateRenderKeys,
  } from '@/views/basic-configuration/components/persoaddmodal';
  import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
  import queryForm from '@/common/components/query-form/index.vue';
  import tableContainer from '@/common/components/table-container/index.vue';
  import secretLevelInfo from '@/common/components/secret-level-info/index.vue';
  // import { sleep } from '@/utils/tools';
  import useFullScreen from '@/common/hooks/fullScreen';
  import { queryAPIRecordListByPage } from '@/api/Basimanagementapi/categorymanagement';
  import { saveByCategory } from '@/api/Basimanagementapi/personnel-matrial';
  import { Message } from '@arco-design/web-vue';

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const attrSelectedKeys = ref([]);

  const cateColumns = ref([
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   width: 120,
    // },
    {
      title: '品类名称',
      dataIndex: 'categoryName',
      width: 120,
    },
    {
      title: '密级',
      dataIndex: 'secretLevel',
      slotName: 'secretLevel',
      width: 120,
    },
    {
      title: '采购件分类',
      dataIndex: 'procurementClassificationName',
      width: 120,
    },
    {
      title: '品类编码',
      dataIndex: 'categoryCode',
      width: 120,
    },
    {
      title: '采购品类层级',
      dataIndex: 'categoryHierarchy',
      width: 120,
    },
  ]);
  const deleteItem = (val, index) => {
    selectAttrList.value.splice(index, 1);
    const itemIndex = attrSelectedKeys.value.findIndex((v) => v === val.id);
    attrSelectedKeys.value.splice(itemIndex, 1);
  };
  const cateDatalist = ref();
  const selectAttrList = ref([]);
  const getQuickAccessList = async (val) => {
    const params = {
      ...val,
    };
    const { data } = await queryAPIRecordListByPage(params);
    const arr = category(data);
    cateDatalist.value = arr;
  };
  const category = (arr) => {
    arr.forEach((v) => {
      if (v.categoryHierarchy !== '三级') {
        v.disabled = true;
      }
      if (v.children !== null) {
        category(v.children);
      }
    });
    return arr;
  };
  onMounted(() => {
    getQuickAccessList();
  });
  const selectItem = (itemList, item, itemObj) => {
    console.log(itemList, item, itemObj);
    // if (itemList.length === 0) {
    //   selectAttrList.value = [];
    //   return;
    // }
    // if (itemList.includes(item)) {
    //   selectAttrList.value.push(itemObj);
    // } else {
    //   const index = selectAttrList.value.findIndex((v) => v.id === item);
    //   console.log(index, 'index');
    //   selectAttrList.value.splice(index, 1);
    // }
  };

  let res = [];
  const findItem = (list, id) => {
    let find = null;
    list.forEach((dataItem) => {
      if (id === dataItem.id) {
        find = dataItem;
        res.push(find);
      } else {
        find = findItem(dataItem.children || [], id);
      }
    });
    return find;
  };
  const handleSelectionChange = (itemList: any) => {
    // debugger;
    res = [];
    console.log(selectAttrList.value.length);
    itemList.forEach((element) => {
      if (selectAttrList.value.find((i) => i.id === element)) {
        res.push(selectAttrList.value.find((i) => i.id === element));
      } else {
        findItem(cateDatalist.value, element);
      }
    });
    console.log(`output->`, res);
    selectAttrList.value = res;
  };
  const size = ref('medium');
  const props = defineProps(['selectPersonalObj']);
  const handleSubmit = async () => {
    if (selectAttrList.value.length === 0) {
      Message.warning('请至少选择一条物料进行操作');
      return;
    }
    const params = [];
    selectAttrList.value.forEach((v) => {
      console.log(v, '000v');
      console.log(props.selectPersonalObj);
      const obj = {
        secretLevel: v.secretLevel,
        userId: props.selectPersonalObj.id,
        categoryLv3Id: v.id,
        userCode: props.selectPersonalObj.userCode,
        userName: props.selectPersonalObj.username,
      };
      params.push(obj);
    });

    const { data } = await saveByCategory(params);
    if (data) {
      Message.success('新增成功');
      handleClose();
    }
    console.log(data);
  };
  const { isFullscreen, screenClass } = useFullScreen();

  const searchHandle = (data: any) => {
    removeEmptyValues(data);
    getQuickAccessList(data);
  };
  const resetHandle = () => {
    getQuickAccessList();
  };
  const removeEmptyValues = (obj) => {
    Object.keys(obj).forEach(function (key) {
      if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj;
  };
  const emit = defineEmits(['close']);
  const editModelShow = ref(true);

  const handleClose = () => {
    emit('close');
  };
</script>

<style lang="less" scoped>
  .onebox {
    // border: 1px solid #000;
    display: flex;
    width: 100%;
  }

  .leftbox {
    width: 400px;
    // border: 1px solid #000;
    // float: left;
  }

  .contentbox {
    width: 900px;
    // border: 1px solid #000;
  }

  .rightbox {
    width: 500px;
    // border: 1px solid #000;
  }

  .spanitem {
    width: 40px;
    height: 18px;
    color: #fff;
    font-size: 10px;
    font-style: normal;
    text-align: center;
    text-transform: none;
    background: #d40000;
    border-radius: 503px;
  }

  .table /deep/.arco-table-container .arco-table-content-scroll-x {
    overflow-y: auto;
  }
</style>
